package fr.afcepf.atod18.fw.controler;

import java.io.IOException;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.Map;
import java.util.Set;

import javax.servlet.ServletConfig;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;







import fr.afcepf.atod18.fw.action.ActionConnexion;
import fr.afcepf.atod18.fw.action.ActionIndex;
import fr.afcepf.atod18.fw.action.ActionInscription;
import fr.afcepf.atod18.fw.action.ActionLogout;
import fr.afcepf.atod18.fw.action.IAction;
import fr.afcepf.atod18.fw.form.ConnexionForm;
import fr.afcepf.atod18.fw.form.IActionForm;
import fr.afcepf.atod18.fw.form.IndexForm;
import fr.afcepf.atod18.fw.form.InscriptionForm;
import fr.afcepf.atod18.fw.form.LogoutForm;


/**
 * Servlet implementation class ServletDispatch
 * Cette servlet constitue le contôleur
 */
public class ActionServlet extends HttpServlet {
    private static final long serialVersionUID = 1L;
    
    private Map<String, Class> mapAction  = new HashMap<String, Class>();
    private Map<String, Class> mapActionForm  = new HashMap<String, Class>();
    private Map<String, String> mapActionErr  = new HashMap<String, String>();
    
    Factory factory;
       
    /**
     * @see HttpServlet#HttpServlet()
     */
    public ActionServlet() {
        super();
        
       
        // TODO Auto-generated constructor stub
    }
    
    
    public void init(ServletConfig config) throws ServletException {
        
        super.init(config);
        
        //Map temporaire juste pour les tests
        mapAction.put("/index.html", ActionIndex.class);
        mapAction.put("/logoutAction.perform", ActionLogout.class);
        mapAction.put("/inscriptionAction.perform", ActionInscription.class);
        mapAction.put("/connexionAction.perform", ActionConnexion.class);
        
        mapActionForm.put("/index.html", IndexForm.class);
        mapActionForm.put("/logoutAction.perform", LogoutForm.class);
        mapActionForm.put("/inscriptionAction.perform", InscriptionForm.class);
        mapActionForm.put("/connexionAction.perform", ConnexionForm.class);
        
        mapActionErr.put("/index.html", "index.jsp");
        mapActionErr.put("/logoutAction.perform", "/pages/error.jsp");
        mapActionErr.put("/inscriptionAction.perform", "/pages/inscription.jsp");
        mapActionErr.put("/connexionAction.perform", "/pages/connexion.jsp");
        
        
        
        factory  = new Factory();
    }

    /**
     * @see HttpServlet#doGet(HttpServletRequest request, HttpServletResponse response)
     */
    protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        
        String suite;
        
        String provenance = request.getServletPath();
        
        // affichage des saisies de la form
        System.out.println("ServletPath=" + request.getServletPath());
        Map<String, String[]> mapParam = request.getParameterMap();
        System.out.println("taille mapParam=" + mapParam.size());
        Set<String> listeKey = mapParam.keySet();
        String ligneSaisie = "";
        for(String key : listeKey) {
            String[] saisie = mapParam.get(key);
            for(int i = 0; i < saisie.length; i++) {
                ligneSaisie += saisie[i];
            }
            System.out.println(key + "=" + ligneSaisie);
        }
        
        Class<IActionForm> formClass = mapActionForm.get(request.getServletPath());
        System.out.println("form=" + formClass);
        
        IActionForm formAction = null;
        try {
            formAction = (IActionForm) formClass.newInstance();
        } catch (InstantiationException | IllegalAccessException e) {
            // TODO Bloc catch généré automatiquement
            e.printStackTrace();
        }
        MyBeanPopulate.populateBean(formAction, mapParam);
        
        System.out.println("populated form=" + formAction);

        IAction a = factory.done(provenance, mapAction );
        
        // Execute action si ActionForm est validé (champs de saisies bien remplie)
        if (formAction.validateForm())
            suite = a.execute(request, response);
        else
            // Recherche dans la map je la page jsp en cas d'erreur:
            // si validation ActionForm echoue
            suite = mapActionErr.get(request.getServletPath());
        
        // Mise à jour dans la page jsp avec un message éventuel et
        // des champs de saisies avec les valeurs des attributs d'un ActionForm 
        request.setAttribute(formAction.getClass().getSimpleName(), formAction);
        
        request.getRequestDispatcher(suite).forward(request, response);
    }

    /**
     * @see HttpServlet#doPost(HttpServletRequest request, HttpServletResponse response)
     */
    protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        doGet( request, response);
    }

}
